<template>
  <div class="info_container">
    <!--个人信息栏-->
    <el-row class="info_row row" :gutter="10">
      <el-col :span="4">
        <div class="area">
          <div class="imgarea">
            <!-- 
              el-upload组件
              1.action属性：指定上传头像的地址
              2.http-request属性：覆盖默认的 Xhr 行为，允许自行实现上传文件的请求，这里主要考虑上传头像需要携带token数据
            -->
            <el-upload
                class="avatar-uploader"
                :action="uploadAction"
                :headers="headerObj"
                :auto-upload="true"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :data="{ provider: 'qiniu' }"
            >           
                <img 
                  v-if="userStore.userInfo.avatar" 
                  :src="getAvatarUrl(userStore.userInfo.avatar)" 
                  class="avatar" 
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <!-- <img src="~@/assets/images/avatar.png" />
            <el-button type="success" size="mini">上传</el-button> -->
          </div>
        </div>

        
      </el-col>

      <el-col :span="5">
        <div class="area">
          <div class="namearea">
            <p>姓名：{{ username }}</p>
            <p>自我介绍：{{ introduction }}</p>
            <!-- <p class="awards">
              <i class="el-icon-date el-icon--left"></i>
              签到有奖
            </p> -->
          </div>
        </div>
      </el-col>

      <!-- <el-col :span="9">
        <div class="area">
          <div class="moneyarea">
            <p class="title">
              可用现金:
              <span class="money">0.00</span>
              <span class="yuan">元</span>
            </p>
          </div>
          <div class="chongzhiarea">
            <img src="~@/assets/images/toMPic02.png" />
            <p class="chongzhi">
              <el-button type="success" size="">我要出借</el-button>
              <el-button type="warning" size="">充值</el-button>
              <el-button type="danger" size="">提现</el-button>
            </p>
          </div>
          <div class="tipsarea">
            <p>
              您的每笔交易资金，都将接受银行全程存管
              <a href="http://www.baidu.com" target="_blank">了解资金存管 》</a>
            </p>
          </div>
        </div>
      </el-col> -->
      <!-- <el-col :span="6">
        <div class="area">
          <div class="dataarea">
            <p class="gtitle">
              <i class="el-icon-date el-icon--left"></i>
              个人数据
            </p>
            <div class="gdataarea clear">
              <div class="gdata left">
                <p class="num">20</p>
                <p class="title">投资数量</p>
              </div>
              <div class="gdata left">
                <p class="num">200</p>
                <p class="title">关注的人</p>
              </div>
              <div class="gdata left">
                <p class="num">3000</p>
                <p class="title">粉丝</p>
              </div>
            </div>
            <p class="morearea">
              谢谢您的关注，
              <a href="http://www.baidu.com" target="_blank">
                了解我的更多个人信息 》
              </a>
            </p>
          </div>
        </div>
      </el-col> -->
    </el-row>
    <!--资金信息栏-->
    <!-- <el-row class="data_row row" :gutter="10">
      <el-col :span="6">
        <div class="area">
          <p class="title">待收资产</p>
          <p class="num">
            <span class="symbol">￥</span>
            78.00
          </p>
          <a class="detail dbgcolor">
            查看详情&nbsp;&nbsp;
            <i class="el-icon-d-arrow-right"></i>
          </a>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="area">
          <p class="title">账户总资产</p>
          <p class="num">
            <span class="symbol">￥</span>
            2078.00
          </p>
          <a class="detail zbgcolor">
            查看详情&nbsp;&nbsp;
            <i class="el-icon-d-arrow-right"></i>
          </a>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="area">
          <p class="title">已得回报</p>
          <p class="num">
            <span class="symbol">￥</span>
            1000.00
          </p>
          <a class="detail dbgcolor">
            查看详情&nbsp;&nbsp;
            <i class="el-icon-d-arrow-right"></i>
          </a>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="area">
          <p class="title">期待回报</p>
          <p class="num">
            <span class="symbol">￥</span>
            3000.00
          </p>
          <a class="detail zbgcolor">
            查看详情&nbsp;&nbsp;
            <i class="el-icon-d-arrow-right"></i>
          </a>
        </div>
      </el-col>
    </el-row> -->
    <!--广告信息栏-->
    <!-- <el-row class="ban_row row" :gutter="10">
      <el-col :span="24">
        <div class="area">
          <ul class="banarea">
            <li v-for="(item, index) in bandata" :key="index">
              <a
                :href="item.url"
                target="_blank"
                :style="{ backgroundPosition: 0 + ' -' + item.data + 'px' }"
              ></a>
            </li>
          </ul>
        </div>
      </el-col>
    </el-row> -->
  </div>
</template>

<script setup>
  import UserAPI from '@/api/system/user.api'
  import { useUserStore } from '@/store/modules/user.store'
  import { ref } from 'vue'
  import FileAPI from '@/api/file.api'
  import { getAccessToken } from "@/utils/auth"
  import { ElMessage } from 'element-plus'
  
  const userStore = useUserStore()
  //console.log(userStore.userInfo)
  const {username , introduction} = userStore.userInfo

  // const bandata = ref([
  //   { url: 'http://www.baidu.com/', data: 300 },
  //   { url: 'http://www.baidu.com/', data: 200 },
  //   { url: 'http://www.baidu.com/', data: 100 },
  //   { url: 'http://www.baidu.com/', data: 0 },
  // ])

  
    
  //处理头像上传
  let imageUrl = ref('')
  
  // 上传相关变量
  const uploadAction = ref('/api/admin/file/upload');
  const headerObj = {
    Authorization: `Bearer ${getAccessToken()}`
  };

// async function upload(f) {
//   try {
//     const formData = new FormData();
//     formData.append("file", f.file);
    
//     // 1. 上传新头像
//     const newAvatarPath = await FileAPI.upload(formData);
    
//     // 2. 更新Pinia存储的用户信息 - 使用正确的方法名 updateAvatar
//     await userStore.updateAvatar(newAvatarPath);   // 这里修改为 updateAvatar
    
//     // 3. 调用API更新后端数据库
//     await UserAPI.updateProfile({ avatar: newAvatarPath });
    
//     // 4. 显示成功消息
//     ElMessage.success("头像更新成功");
//   } catch (error) {
//     ElMessage.error("头像更新失败：" + (error.message || "未知错误"));
//   }
// }
// 获取头像URL
function getAvatarUrl(avatar) {
  if (!avatar) {
    return ''; // 返回默认头像或空字符串
  }
  
  // 如果已经是完整的URL（七牛云返回的），直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar;
  }
  
  // 如果是相对路径，拼接本地服务器地址
  return `http://localhost:8080${avatar}`;
}

// 头像上传成功回调
const handleAvatarSuccess = async (response, file) => {
  console.log('上传成功响应:', response);
  console.log('上传的文件:', file);
  
  // 处理响应格式
  let avatarUrl = '';
  if (typeof response === 'string') {
    avatarUrl = response;
  } else if (response && typeof response === 'object') {
    // 如果是对象，尝试获取data字段
    avatarUrl = response.data || response.url || '';
  }
  
  if (avatarUrl) {
    try {
      // 更新用户头像 - 使用update方法，用户ID为1
      await UserAPI.update(1, { avatar: avatarUrl });
      
      // 更新本地状态
      userStore.userInfo.avatar = avatarUrl;
      
      ElMessage.success("头像更新成功");
    } catch (error) {
      console.error("更新头像失败:", error);
      ElMessage.error("头像更新失败: " + (error.message || "未知错误"));
    }
  } else {
    console.error("上传失败：响应格式不正确", response);
    ElMessage.error("上传失败：未获取到文件URL");
  }
};



  //头像上传之前的回调，一般用来限制上传文件的格式、大小等
  const beforeAvatarUpload = (rawFile) => {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(rawFile.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF、WebP 格式的图片');
      return false;
    }

    // 验证文件大小 (5MB)
    const maxSize = 5 * 1024 * 1024;
    if (rawFile.size > maxSize) {
      ElMessage.error('图片大小不能超过 5MB');
      return false;
    }

    return true;
  }
</script>

<style lang="scss" scoped>
.info_container {
  padding: 10px;
  margin: 0 10px;
  overflow: auto;
}
.row {
  margin: 20px;
}
.info_row {
  .area {
    border: 1px solid #dfdfdf;
    height: 210px;
    overflow: hidden;
    .imgarea {
      text-align: center;
      padding: 10px;
      img {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        margin-bottom: 20px;
      }
    }
    .namearea {
      padding: 10px;
      font-size: 14px;
      p {
        line-height: 54px;
      }
      .awards {
        margin-top: 20px;
        text-align: center;
        width: 100%;
        height: 30px;
        line-height: 30px;
        cursor: pointer;
        background-color: #3bc5ff;
        border: 1px solid #3bc5ff;
        color: white;
        display: block;
      }
      .awards:hover {
        background-color: #f9c855;
        border: 1px solid #f9c855;
      }
    }
    .moneyarea {
      padding: 10px;
      float: left;
      .title {
        font-size: 15px;
        font-weight: bolder;
        line-height: 25px;
        .money {
          color: #c10000;
          margin-right: 5px;
        }
        .yuan {
          font-weight: 100;
          font-size: 13px;
        }
      }
    }
    .chongzhiarea {
      padding: 10px;
      text-align: center;
      img {
        width: 80%;
        height: 40px;
      }
      .chongzhi {
        margin-top: 10px;
      }
    }
    .tipsarea {
      clear: both;
      font-size: 14px;
      padding: 10px;
      padding-top: 15px;
      a {
        color: #3bc5ff;
      }
    }
    .dataarea {
      padding: 10px;
      text-align: center;
      font-size: 14px;
      .gtitle {
        width: 100%;
        height: 30px;
        line-height: 30px;
        cursor: pointer;
        background-color: #3bc5ff;
        color: white;
        display: block;
      }
      .gdataarea {
        padding-left: 25px;
        p {
          line-height: 20px;
        }
        .num {
          font-weight: bolder;
          color: #c10000;
        }
        .title {
          color: #3bc5ff;
        }
        .gdata {
          margin: 10px;
        }
      }
      .morearea {
        a {
          color: #3bc5ff;
        }
      }
    }
  }
}
.data_row {
  font-size: 18px;
  .area {
    border: 1px solid #dfdfdf;
    height: 200px;
    overflow: hidden;
    padding: 10px;
    text-align: center;
    font-weight: bolder;
    .fa {
      margin-right: 10px;
    }
    .symbol {
      font-size: 16px;
      font-style: italic;
      font-family: 'microsoft yahei';
      margin-right: 10px;
      color: #232323;
      font-weight: 100;
    }
    p {
      line-height: 70px;
    }
    .num {
      color: #c10000;
    }
    .detail {
      margin-top: 5px;
      font-size: 14px;
      text-align: center;
      width: 100%;
      height: 30px;
      line-height: 30px;
      cursor: pointer;
      color: white;
      display: block;
      border: 1px solid #3bc5ff;
    }
    .dbgcolor {
      background-color: #3bc5ff;
    }
    .zbgcolor {
      color: #3bc5ff;
    }
    .dbgcolor:hover {
      background-color: #fff;
      color: #3bc5ff;
    }
    .zbgcolor:hover {
      background-color: #3bc5ff;
      color: #fff;
    }
  }
}
.ban_row {
  .area {
    padding-left: 4%;
    .banarea {
      li {
        float: left;
        width: 200px;
        margin: 30px;
        a {
          background: url(../../assets/images/pro_map.gif?v=1.0) no-repeat;
          width: 200px;
          height: 50px;
          display: block;
        }
      }
    }
  }
}
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  text-align: center;
}
</style>
